<?php

namespace App\Console\Commands;

use App\Model\Order;
use App\Model\Order1;
use App\Model\PushOrder;
use Illuminate\Console\Command;

class fuluPush extends Command
{
    //正式
    private $url = "http://openapi.fulu.com/api/getway";

    //品盛
//    private $app_key = "YZ2Fu5Y86kfnF4qIcKCtOK9PjJzlv4w7kq+bPPu0SmeZxjqn5gUBgTAthCnxFOXP";
//    private $app_secret = "10888069844749068c5f6fe742796e0b";

    //普兴
//    private $app_key = "k62nIJvlYq9lhEQfrmC1dWhavZFQCsJNX/iC9ivhTnmwjppWUrl28EjHts2tGTZg";
//    private $app_secret = "b6888a54dfa143ab9f69f035b831d60d";

    //竹清
    private $app_key = "5aN/mSAIt3TKzydo+CETbqGduinUqPfksmCm60034GyF2S8su68+au0Dr3uJa31F";
    private $app_secret = "2f887bdc2f5b4151b8b06d52a628a52b";

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fuluPush';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while(true){
            try {
                $order = Order::where(['isok' => "6"])->first();
                if ($order) {
                    switch ($order['price']) {
                        case 50:
                            $product_id = 500060707;
                            break;
                        case 100:
                            $product_id = 500060708;
                            break;
                        case 200:
                            $product_id = 500060709;
                            break;
                        case 300:
                            $product_id = 500060710;
                            break;
                        case 500:
                            $product_id = 500060712;
                            break;
                        case 1000:
                            $product_id = 500060713;
                            break;
                    }
                    $resFulu = $this->pushOrderFulu($product_id, $order['orderno'], $order['chargeaccount'], $order['num']);
                    if ($resFulu->code == 0) {
                        $infoFulu['branch'] = '已推送快充';
                        $infoFulu['status'] = '已处理';
                        $infoFulu['isok'] = 4;
                        $infoFulu['bid'] = 888;
                        $infoFulu['time'] = time();
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        Order1::where('orderno', $order['orderno'])->update($infoFulu);
                    } else {
                        $failInfo = '';
                        switch ($resFulu->code) {
                            case    2004:
                                $failInfo = "商户余额不足";
                                break;
                            case    3001:
                                $failInfo = "商品不存在或无法购买";
                                break;
                            case    3002:
                                $failInfo = "商品已下架";
                                break;
                            case    3003:
                                $failInfo = "商品维护中";
                                break;
                            case    3004:
                                $failInfo = "商品在维护期内";
                                break;
                            case    3005:
                                $failInfo = "商品库存不足";
                                break;
                            case    4004:
                                $failInfo = "充值账号在黑名单中";
                                break;
                            case    4010:
                                $failInfo = "外部订单号已存在";
                                break;
                        }
                        $infoFulu['branch'] = $resFulu->code . $failInfo;
                        $infoFulu['status'] = '查询福禄失败原因';
                        $infoFulu['isok'] = 3;
                        $infoFulu['bid'] = 0;
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        Order1::where('orderno', $order['orderno'])->update($infoFulu);
                    }
                }
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
            $this->orderInfo();
            sleep(10);
        }
    }

    //定时查询福禄充值状态
    public function orderInfo()
    {
        $orders = PushOrder::where(["isok" => 4])->get();
        foreach ($orders as $order) {
            $url = "http://112.124.24.221/admin/callback/getOrderInfo?id=" . $order['orderno'] . "&table=PushOrder";
            $this->curlGet($url, 'get');
        }

        $orders = Order::where(["isok" => 4])->get();
        foreach ($orders as $order) {
            $url = "http://112.124.24.221/admin/callback/getOrderInfo?id=" . $order['orderno'] . "&table=Order";
            $this->curlGet($url, 'get');
        }
    }

    public function curlGet($url, $method, $post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } elseif ($method == 'get') {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
//        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1");
//        curl_setopt($ch, CURLOPT_PROXYPORT, "2802");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //下单到福禄
    public function pushOrderFulu($product_id, $customer_order_no, $charge_account, $buy_num = 1)
    {
        $param = [
            "product_id" => $product_id,
            "customer_order_no" => $customer_order_no,
            "charge_account" => $charge_account,
            "buy_num" => $buy_num
        ];

        $data = [
            "app_key" => $this->app_key,
            "method" => "fulu.order.direct.add",
            "timestamp" => date("Y-m-d H:i:s", time()),
            "version" => "2.0",
            "format" => "json",
            "charset" => "utf-8",
            "sign_type" => "md5",
            "app_auth_token" => "",
            "biz_content" => json_encode($param),
        ];
        $sign = $this->getSign($data);

        $data['sign'] = $sign;

        $res = $this->curlFulu($this->url, json_encode($data, JSON_UNESCAPED_SLASHES));

        $res = json_decode($res);

        return $res;

    }

    public function curlFulu($url, $post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getSign($Parameters)
    {
        //签名步骤一：把字典json序列化
        $json = json_encode($Parameters, JSON_UNESCAPED_SLASHES);
        //签名步骤二：转化为数组
        $jsonArr = $this->mb_str_split($json);
        //签名步骤三：排序
        sort($jsonArr);
        //签名步骤四：转化为字符串
        $string = implode('', $jsonArr);
        //签名步骤五：在string后加入secret
        $string = $string . $this->app_secret;
        //签名步骤六：MD5加密
        $result_ = strtolower(md5($string));
        return $result_;
    }

    function mb_str_split($str)
    {
        return preg_split('/(?<!^)(?!$)/u', $str);
    }
}
